import {
  DatePicker,
  Input,
  Table,
  message,
  Form,
  Select,
  Row,
  Col,
  InputNumber,
  Space,
  AutoComplete,
} from 'antd';
import Button from 'antd/es/button';
import { ColumnsType } from 'antd/es/table/interface';
import { FetchDataParam, FetchDataResponse, PageSelect } from 'components/UILibrary/pageSelect';
import moment from 'moment';
import React from 'react';

import { HandleColInfo } from 'admin/schema/Task';
import {
  getCallRecordCol,
  modifyCallRecordCol,
  getCallRecordsReportList,
  createCallRecordDownloadTask,
  getRobots,
  refreshHistoryRecords,
} from 'admin/servers/servers';
import { clearNull, getTableIndex } from 'utils/tools';
import { checkPermission } from 'permission/Index';
import { CustomCol } from 'admin/pages/Task/components/CustomCol';
import {
  callStatusOption,
  flowTypeOption,
  getCallStatusName,
  getCallTypeOption,
  getHangupDirectName,
  getSoundTypeOption,
  getTaskFlowTypeName,
  getTransferManualStatusName,
  getUserIntentionOption,
  transferManualStatusOption,
} from 'admin/pages/Task/components/TaskTool';
import {
  CallrecordsReportRequest,
  CallrecordsReportResponse,
} from 'admin/schema/CallRecordsReport';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { CallRecordDetailDrawer } from 'components/CallRecordDetailDrawer';
const { RangePicker } = DatePicker;
import './style.scss';

interface IProp {}

interface IState {
  // 搜索条件
  /**
   * 任务名称
   */
  taskName?: string;
  /**
   * 呼叫号码
   */
  phoneNumber?: string;
  /**
   * 流程分类  0:机器人流程，1：通知流程，2：人机协同，3：人工自动外呼
   */
  flowType?: number;
  /**
   * 通话状态
   */
  callStatus?: number[];
  /**
   * 开始时间
   */
  beginTime?: string;
  /**
   * 结束时间
   */
  endTime?: string;
  /**
   * 机器人名称
   */
  robotName?: string;
  /**
   *转接人工状态：0：未转；1：成功；2：失败
   */
  transferManualStatus?: number[];
  /**
   * 通话时长范围-最小值
   */
  callTalkTimeMin?: number;
  /**
   * 通话时长范围-最大值
   */
  callTalkTimeMax?: number;
  /** table列头 */
  tableColumns: ColumnsType<CallrecordsReportResponse>;
  /** 定制列应用的结构 */
  customCol: HandleColInfo[];
  tableData: CallrecordsReportResponse[];
  // 分页相关数据
  pageInfo: {
    pageTotal: number;
    pageNum: number;
    pageSize: number;
  };
  downloadTaskId?: number;
  fileName?: string;
  fileUrl?: string;
  expand: boolean;
  tableLoading: boolean;
  robotOptions: {
    label: string;
    value: string;
  }[];
  targetRecord: any; // 当前选中列
  targetRecordIdx: any; // 当前选中列 index
}

export default class CallRecordReport extends React.Component<IProp, IState> {
  /**记录详情 */
  private callRecordRef: React.RefObject<CallRecordDetailDrawer>;
  /**定制列 */
  private customColRef: React.RefObject<CustomCol>;
  /**通话结果 */
  private statusSelectRef: React.RefObject<PageSelect>;
  /**转人工状态 */
  private transferManualStatusSelectRef: React.RefObject<PageSelect>;
  /** 请选择机器人 */
  private robotRef: React.RefObject<any>;
  constructor(arg: IProp) {
    super(arg);
    this.callRecordRef = React.createRef();
    this.customColRef = React.createRef();
    this.statusSelectRef = React.createRef();
    this.transferManualStatusSelectRef = React.createRef();
    this.robotRef = React.createRef();
    this.state = {
      flowType: -1,
      callStatus: undefined,
      transferManualStatus: undefined,
      tableData: [],
      pageInfo: {
        pageTotal: 0,
        pageNum: 1,
        pageSize: 10,
      },
      customCol: [],
      tableColumns: [],
      expand: false,
      tableLoading: false,
      robotOptions: [],
      targetRecord: {},
      targetRecordIdx: 0,
    };
  }

  componentDidMount() {
    this.fetchCol();
    this.fetchList();
    this.statusSelectRef.current?.selectAll();
  }
  componentWillUnmount() {
    this.setState = (state, callback) => {
      return;
    };
  }
  /* 自定义-列渲染-【通话记录定制列】 */
  private renderTableCols(item: any) {
    const obj = {
      title: item.desc,
      key: item.columnName,
      dataIndex: item.columnName,
      ellipsis: true,
      render: (text: any, record: CallrecordsReportResponse, index: number) => {
        return text;
      },
    };
    // 前端显示（特殊列-处理）
    switch (item.columnName) {
      case 'callStatus':
        obj.render = text => getCallStatusName(text);
        break;
      case 'callType':
        obj.render = text => getCallTypeOption(text);
        break;
      case 'soundType':
        obj.render = text => getSoundTypeOption(text);
        break;
      case 'hangupDirect':
        obj.render = text => getHangupDirectName(text);
        break;
      case 'transferManualStatus':
        obj.render = text => getTransferManualStatusName(text);
        break;
      case 'flowType':
        obj.render = text => getTaskFlowTypeName(text);
        break;
      case 'userIntentionDegree':
        obj.render = text => getUserIntentionOption(text);
        break;
      default:
        break;
    }
    return obj;
  }

  /**获取呼叫结果-下拉列表数据-前端拼接，无后端接口返回 */
  private fetchCallResultOptions(arg: FetchDataParam): FetchDataResponse {
    return Promise.resolve({
      data: callStatusOption,
      total: callStatusOption.length,
    });
  }
  /**获取转人工状态-下拉列表数据-前端拼接，无后端接口返回 */
  private fetchTransferManualStatusOptions(arg: FetchDataParam): FetchDataResponse {
    return Promise.resolve({
      data: transferManualStatusOption,
      total: transferManualStatusOption.length,
    });
  }
  /**
   * 展开通话记录详情
   */
  private showDetail(index: number, record: CallrecordsReportResponse) {
    // console.log('showDetail', index, record);
    const {
      pageInfo,
      taskName,
      phoneNumber,
      flowType,
      callStatus,
      beginTime,
      endTime,
      robotName,
      transferManualStatus,
      callTalkTimeMin,
      callTalkTimeMax,
    } = this.state;
    const { pageNum, pageSize, pageTotal } = pageInfo;
    const searchParms = {
      pageTotal,
      pageNo: (pageNum - 1) * pageSize + (index + 1), // 根据列表计算当前条位置
      pageSize: 1, // 按每条1页展示
      taskName,
      phoneNumber,
      flowType: flowType !== -1 ? flowType : undefined,
      callStatus,
      beginTime,
      endTime,
      robotName,
      transferManualStatus,
      callTalkTimeMin,
      callTalkTimeMax,
    };
    this.setState({
      targetRecord: record,
      targetRecordIdx: index,
    });
    this.callRecordRef.current?.show(searchParms, record);
  }

  // 刷新列表查询会话历史记录（刷新加载全部历史聊天，修复不全聊天记录）
  refreshRecordHistory = async () => {
    const callRecordId = this.state.targetRecord.callRecordId;
    // console.log('加载全部历史聊天', callRecordId);
    await refreshHistoryRecords(callRecordId).catch(err => {
      console.error(err);
    });

    await this.fetchList();

    const { tableData, targetRecord } = this.state;
    // console.log('tableData', tableData, targetRecord);
    const idx = tableData.findIndex(i => i.callRecordId === targetRecord.callRecordId);
    // console.log('idx', idx);
    if (idx !== -1) {
      message.success('刷新成功');
      this.callRecordRef.current?.hide();
      this.showDetail(idx, tableData[idx]);
      this.callRecordRef.current?.forceUpdate?.();
    } else {
      console.error('刷新后未找到之前打开的指定的列表');
    }
  };

  /**
   * 查询table数据
   */
  private async fetchList() {
    this.setState({
      tableLoading: true,
    });
    const {
      pageInfo,
      taskName,
      phoneNumber,
      flowType,
      callStatus,
      beginTime,
      endTime,
      robotName,
      transferManualStatus,
      callTalkTimeMin,
      callTalkTimeMax,
    } = this.state;

    try {
      const params = {
        pageNo: pageInfo.pageNum,
        pageSize: pageInfo.pageSize,
        taskName,
        phoneNumber,
        flowType: flowType !== -1 ? flowType : undefined,
        callStatus,
        beginTime,
        endTime,
        robotName,
        transferManualStatus,
        callTalkTimeMin,
        callTalkTimeMax,
      };
      const res = await this.fetchCallRecord(params);
      pageInfo.pageTotal = res.count as number;
      this.setState({
        tableData: res.data,
        pageInfo: pageInfo,
      });
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    this.setState({
      tableLoading: false,
    });
  }
  /**请求数据-单独，方便详情页调用 */
  private async fetchCallRecord(params: CallrecordsReportRequest) {
    const res = await getCallRecordsReportList(clearNull(params));
    return res;
  }

  /**
   * 获取列头信息
   */
  private fetchCol() {
    getCallRecordCol()
      .then(res => {
        /**后端返回的table列头信息，包含switch信息 */
        const originData = res.data;
        /**定制列信息 */
        const custom_cols: HandleColInfo[] = [];
        /**表格列 */
        const table_cols: ColumnsType<CallrecordsReportResponse> = [];
        // 遍历列数据
        originData.forEach((item, index) => {
          // console.log("原始-列信息-", item);
          item.desc = item.desc ? item.desc : '列-' + item.columnName;
          // 定制列，存储所有列
          custom_cols.push({
            title: item.desc,
            key: item.columnName,
            switch: item.switch,
          });
          // table，只查找为on的列，存入table列展示
          if (!item.switch || item.switch !== 'on') {
            return;
          }
          const obj = this.renderTableCols(item);
          table_cols.push(obj);
        });

        /**表格第一列：序号列 */
        const index_col: any = {
          title: '序号',
          key: 'index',
          dataIndex: 'index',
          fixed: 'left',
          width: 70,
          render: (text: any, record: CallrecordsReportResponse, index: number) =>
            getTableIndex(index, this.state.pageInfo.pageSize, this.state.pageInfo.pageNum),
        };

        /**表格最后一列：操作列 */
        const operation_col = {
          title: '操作',
          key: 'opearation',
          fixed: 'right',
          width: 80,
          render: (text: any, record: CallrecordsReportResponse, index: number) => {
            return (
              <>
                <Button
                  type="link"
                  onClick={() => {
                    this.showDetail(index, record);
                  }}
                >
                  详情
                </Button>
              </>
            );
          },
        };
        /**数据源：表格列;switch为on，包含，序号，操作列 */
        const table_columns: any = [index_col, ...table_cols, operation_col];
        console.log('table_columns', table_columns);
        this.setState({
          customCol: custom_cols,
          tableColumns: table_columns,
        });
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }
  /**
   * 表格行操作后，重置列表
   */
  private resetList() {
    this.jumpPage(1);
  }
  /**
   * 跳页方法
   */
  private jumpPage(pageNum: number, pageSize?: number): void {
    const newProp = this.state.pageInfo;
    newProp.pageNum = pageNum;
    if (pageSize) {
      newProp.pageSize = pageSize;
    }
    this.setState(
      {
        pageInfo: newProp,
      },
      () => {
        this.fetchList();
      }
    );
  }

  /**
   * @private 时间范围选择器-绑定onChange事件
   * @param {*} dates moment格式
   * @param {*} dateStrings dateFormate格式
   * @memberof CallTask
   */
  private onDateChange(dates: any, dateStrings: any) {
    console.log(dates, '选择的日期范围', dateStrings);
    this.setState({
      beginTime: dateStrings[0],
      endTime: dateStrings[1],
    });
  }

  /**
   * 打开定制列对话框
   */
  private handleColumn(): void {
    this.customColRef.current?.show();
    this.customColRef.current?.setCol(this.state.customCol);
  }

  /**
   * 处理查询任务状态条件变更
   */
  private onStatusChange(val: { label: string; value: number }[]): void {
    const status = val.length === 0 || val.length === 23 ? undefined : val.map(item => item.value);
    this.setState({
      callStatus: status,
    });
  }
  /**
   * 处理查询任务转人工状态条件变更
   */
  private onTransferManualStatusChange(val: { label: string; value: number }[]): void {
    this.setState({
      transferManualStatus:
        val.length === 0 || val.length === 3 ? undefined : val.map(item => item.value),
    });
  }

  private handleExport(): void {
    // 创建下载任务
    const {
      taskName,
      phoneNumber,
      flowType,
      callStatus,
      beginTime,
      endTime,
      robotName,
      transferManualStatus,
      callTalkTimeMin,
      callTalkTimeMax,
    } = this.state;
    const postData = clearNull({
      callStatus,
      beginTime,
      endTime,
      taskName,
      phoneNumber,
      flowType: flowType !== -1 ? flowType : undefined,
      robotName,
      transferManualStatus,
      callTalkTimeMin,
      callTalkTimeMax,
    });
    createCallRecordDownloadTask(postData as any).then(res => {
      if (res.code === 0) {
        // 创建下载任务
        message.warning('数据正在准备中，请稍候到下载管理中下载');
      } else {
        message.error(`${res.tips}(错误码:${res.code})`);
      }
    });
  }

  /**初始化机器人列表 */
  initRobotList = () => {
    getRobots(
      clearNull({
        pageNo: 1,
        pageSize: 10000,
      })
    )
      .then(res => {
        this.setState({
          robotOptions:
            res.data?.map(item => {
              return {
                label: item.robotName,
                value: item.robotName,
              };
            }) || [],
        });
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  };

  /**
   * 重置搜索列表
   */
  private resetSearch() {
    // 重置搜索条件；重置列表
    this.setState({
      taskName: undefined,
      phoneNumber: undefined,
      flowType: -1,
      transferManualStatus: [],
      callStatus: [],
      beginTime: undefined,
      endTime: undefined,
      robotName: undefined,
      callTalkTimeMin: undefined,
      callTalkTimeMax: undefined,
    });
    this.jumpPage(1);
    this.statusSelectRef.current?.selectAll();
    this.transferManualStatusSelectRef.current?.selectAll();
  }
  /**展开收缩 */
  private expand(expand: boolean) {
    this.setState(
      {
        expand: !expand,
      },
      () => {
        const { transferManualStatus } = this.state;
        if (transferManualStatus?.length) {
          this.transferManualStatusSelectRef.current?.setValueWithoutPage(transferManualStatus);
        } else {
          this.transferManualStatusSelectRef.current?.selectAll();
        }
      }
    );
  }
  render() {
    const {
      customColRef,
      statusSelectRef,
      transferManualStatusSelectRef,
      callRecordRef,
      state: {
        tableColumns,
        tableData,
        pageInfo: { pageNum, pageSize, pageTotal },
        taskName,
        phoneNumber,
        flowType,
        beginTime,
        endTime,
        callTalkTimeMin,
        callTalkTimeMax,
        expand,
        tableLoading,
        robotOptions,
        robotName,
      },
    } = this;

    return (
      <>
        <div className="mgr-header callrecord-report-header" id="area">
          <div className="mgr-header-left">
            <Form>
              <Row gutter={24}>
                <Col md={12} xl={8} xxl={8}>
                  <Form.Item label="任务名称">
                    <Input
                      value={taskName}
                      placeholder="请输入任务名称"
                      onChange={e => {
                        this.setState({ taskName: e.target.value.trim() });
                      }}
                    />
                  </Form.Item>
                </Col>
                <Col md={12} xl={8} xxl={5}>
                  <Form.Item label="任务类型">
                    <Select
                      value={flowType}
                      options={flowTypeOption}
                      onChange={val => {
                        this.setState({ flowType: val });
                      }}
                    />
                  </Form.Item>
                </Col>
                <Col md={12} xl={8} xxl={5}>
                  <Form.Item label="呼叫号码">
                    <Input
                      value={phoneNumber}
                      maxLength={15}
                      placeholder="请输入呼叫号码"
                      allowClear
                      onChange={e => {
                        this.setState({ phoneNumber: e.target.value.replace(/[^0-9]+/g, '') });
                      }}
                    />
                  </Form.Item>
                </Col>
                <Col md={12} xl={8} xxl={6}>
                  <Form.Item label="呼叫结果">
                    <PageSelect
                      ref={statusSelectRef}
                      fetchData={this.fetchCallResultOptions}
                      multiChoice={true}
                      pageSize={10000}
                      showCheckBox={true}
                      onChange={val => {
                        this.onStatusChange(val as any);
                      }}
                      showOutsideItem={false}
                    />
                  </Form.Item>
                </Col>
                <Col md={12} xl={8} xxl={8}>
                  <Form.Item label="呼叫时间">
                    <RangePicker
                      showTime
                      format="YYYY-MM-DD HH:mm:ss"
                      value={beginTime && endTime ? [moment(beginTime), moment(endTime)] : null}
                      ranges={{
                        今天: [moment().startOf('day'), moment().endOf('day')],
                        本周: [moment().startOf('week'), moment().endOf('week')],
                        本月: [moment().startOf('month'), moment().endOf('month')],
                      }}
                      onChange={this.onDateChange.bind(this)}
                      allowClear
                    />
                  </Form.Item>
                </Col>
                {expand ? (
                  <>
                    <Col md={12} xl={8} xxl={5}>
                      <Form.Item label="机器人">
                        <AutoComplete
                          value={robotName}
                          getPopupContainer={(): any => document.getElementById('area')}
                          dropdownClassName="my-auto-search-dropdown"
                          allowClear
                          options={robotOptions}
                          placeholder="请输入机器人名称"
                          filterOption={(inputValue, option) =>
                            option?.value.indexOf(inputValue) !== -1
                          }
                          onFocus={this.initRobotList}
                          onChange={(val: any) => {
                            console.log(val, '机器人选择');
                            this.setState({
                              robotName: val?.trim(),
                            });
                          }}
                        />
                      </Form.Item>
                    </Col>
                    <Col md={12} xl={8} xxl={5}>
                      <Form.Item label="转人工状态">
                        <PageSelect
                          ref={transferManualStatusSelectRef}
                          fetchData={this.fetchTransferManualStatusOptions}
                          multiChoice={true}
                          pageSize={10000}
                          showCheckBox={true}
                          onChange={val => {
                            this.onTransferManualStatusChange(val as any);
                          }}
                          showOutsideItem={false}
                        />
                      </Form.Item>
                    </Col>
                    <Col md={12} xl={12} xxl={6}>
                      <Form.Item label="通话时长">
                        <Space>
                          <InputNumber
                            min={0}
                            max={99999999}
                            value={callTalkTimeMin}
                            precision={0}
                            placeholder="最小值"
                            onChange={(val: any) => {
                              let newVal = val;
                              // 当最小值大于最大值，自动恢复为最大值
                              if (callTalkTimeMax && val > callTalkTimeMax) {
                                newVal = callTalkTimeMax;
                              }
                              this.setState({ callTalkTimeMin: newVal });
                            }}
                          />
                          -
                          <InputNumber
                            min={callTalkTimeMin}
                            max={99999999}
                            value={callTalkTimeMax}
                            precision={0}
                            placeholder="最大值"
                            onChange={(val: any) => {
                              this.setState({ callTalkTimeMax: val });
                            }}
                          />
                          秒
                        </Space>
                      </Form.Item>
                    </Col>
                  </>
                ) : null}
              </Row>
            </Form>
          </div>
          <div className="mgr-header-right">
            <Row gutter={24}>
              <Col span={24}>
                <Button
                  type="primary"
                  onClick={() => {
                    this.resetList();
                  }}
                >
                  搜索
                </Button>
                <Button
                  type="primary"
                  ghost
                  onClick={() => {
                    this.resetSearch();
                  }}
                >
                  重置
                </Button>
                <Button
                  type="link"
                  style={{ fontSize: 12, width: 40, padding: 0 }}
                  onClick={() => this.expand(expand)}
                >
                  {expand ? (
                    <>
                      收起
                      <UpOutlined />
                    </>
                  ) : (
                    <>
                      展开
                      <DownOutlined />
                    </>
                  )}
                </Button>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col span={24}>
                <Button
                  type="primary"
                  onClick={() => {
                    this.handleColumn();
                  }}
                >
                  定制列
                </Button>
                {checkPermission('/report/callRecords/export') && (
                  <Button
                    type="primary"
                    onClick={() => {
                      this.handleExport();
                    }}
                  >
                    导出
                  </Button>
                )}
              </Col>
            </Row>
          </div>
        </div>
        <div className="mgr-table">
          <Table
            loading={tableLoading}
            dataSource={tableData}
            scroll={{ x: 'max-content' }}
            columns={tableColumns}
            rowKey="callRecordId"
            pagination={{
              showSizeChanger: true,
              total: pageTotal,
              showTotal: total => `共 ${total} 条`,
              current: pageNum,
              pageSize: pageSize,
              onChange: (pageNum, pageSize) => {
                this.jumpPage(pageNum, pageSize as number);
              },
            }}
          />
        </div>
        <CallRecordDetailDrawer
          ref={callRecordRef}
          showRefresh={true}
          fetchRecord={this.fetchCallRecord.bind(this)}
          refreshRecordHistory={this.refreshRecordHistory}
        />
        <CustomCol
          callback={res => {
            modifyCallRecordCol(res)
              .then(response => {
                message.success('编辑成功');
                this.fetchCol();
              })
              .catch(error => {
                console.error(`系统异常: ${JSON.stringify(error)}`);
              });
          }}
          ref={customColRef}
        />
      </>
    );
  }
}
